package com.togo.algorithm.easy.link;

import com.togo.algorithm.common.ListNode;
import com.togo.algorithm.util.ListNodeUtil;

/**
 * @Author taiyn
 * @Description 定义一个函数，输入一个链表的头节点，反转该链表并输出反转后链表的头节点。
 * <p>
 *  
 * <p>
 * 示例:
 * <p>
 * 输入: 1->2->3->4->5->NULL
 * 输出: 5->4->3->2->1->NULL
 * @Date 3:06 PM 2023/5/23
 **/
public class Offer24 {

    public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) return head;

        ListNode cur = head;
        ListNode pre = null;
        while (cur != null) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }

        return pre;
    }

    public ListNode reverseListByRecur(ListNode head) {
        return recur(head, null);
    }

    private ListNode recur(ListNode cur, ListNode pre) {
        if (cur == null) return pre;

        ListNode tmp = cur.next;
        cur.next = pre;

        return recur(tmp, cur);
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        ListNode listNode = ListNodeUtil.buildByArray(arr);
        Offer24 offer24 = new Offer24();
        ListNode head = offer24.reverseList(listNode);

        ListNodeUtil.print(head);

        ListNode head1 = offer24.reverseListByRecur(head);
        ListNodeUtil.print(head1);
    }
}
